package base.service.impl;

import base.mapper.MailVerifyMapper;
import base.mapper.UserInfoMapper;
import base.pojo.MailVerify;
import base.pojo.UserInfo;
import base.service.IEmailService;
import base.service.IUserInfoService;
import common.Const;
import common.ServerResponse;
import common.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.BitOperationUtil;
import util.DateUtil;
import util.SendEmailUtil;

import java.util.Date;
import java.util.UUID;

@Service
public class EmailServiceImpl implements IEmailService
{

    @Autowired
    MailVerifyMapper    mailVerifyMapper;
    @Autowired
    IUserInfoService    iUserInfoService;
    @Autowired
    SendEmailUtil       sendEmailUtil   ;
    
    public ServerResponse checkEmail(String email)
    {
        if(iUserInfoService.checkEmil(email)>0)
        {
            return ServerResponse.createByErrorMsg("该邮箱地址已被绑定,请更换邮箱")       ;
        }
        return ServerResponse.createBySuccess();
    }

    public ServerResponse sendEmail(String email) throws Exception {
        MailVerify mailVerifys      =   mailVerifyMapper.getEmailByEmail(email)         ;
        if(mailVerifys != null)
        {
            Date oldTime            =   mailVerifys.getDeadline()                       ;
            Date newTime            =   new Date()                                      ;
            long times              =   DateUtil.secondsBetween(oldTime,newTime)        ;
            int  hour               =   (int) (times/60/60)                             ;
            if(hour  <   48)
            {
                return ServerResponse.createByErrorMsg("请勿重复提交绑定请求")           ;
            }
            mailVerifyMapper.deleteByPrimaryKey(mailVerifys.getId())                    ;
        }

        ServerResponse sr   =   checkEmail(email);
        if(sr.getStatus()   !=  0)
        {
            return sr                            ;
        }
        //发送验证码逻辑
        MailVerify mailVerify   =   new MailVerify()                    ;
        mailVerify.setUserInfoId(UserContext.getCurrentUser().getId())  ;
        mailVerify.setEmail(email)                                      ;
        String randomCode   =  UUID.randomUUID().toString()             ;
        mailVerify.setRandomCode(randomCode)                            ;
        mailVerify.setDeadline(new Date())                              ;
        StringBuilder stringBuilder =   new StringBuilder()             ;
        stringBuilder.append("<tr><td style='padding:10px 0;text-indent:25px;'><b>欢迎加入P2P金融系统!</b></td>")
                .append("</tr><tr><td style='padding:10px 0;text-indent:25px;line-height: 10px;'><p>亲爱的用户，你好!</p>")
                .append("<p>你的验证邮箱是：<b><a href='mailto:"+email+"' target='_blank'>"+email+"</a></b></p>")
                .append("</td></tr><tr><td style='padding:10px 0;text-indent:25px;'>请点击以下链接验证你的邮箱地址!(48小时内有效) </td></tr>")
                .append("<tr><td style='padding:10px 0;text-indent:25px;'><a style='color:#1e88e5;text-decoration: none;' href='http://localhost:8080/bindEmail.do?checkCode="+randomCode+"' target='_blank'>http://localhost:8080/bindEmail.do?checkCode="+randomCode+"</a></td></tr>")
                .append("<tr><td style='padding:10px 0;text-indent:25px;'>如果以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。</td>")
                .append("</tr><tr><td style='padding:10px 0 20px 0;text-indent:25px;line-height: 10px;'>")
                .append("<p>祝您生活愉快，工作顺利！</p><p>P2P团队敬上</p></td></tr>")           ;
        sendEmailUtil.sendEmail(email,"P2P金融系统-邮箱绑定验证",stringBuilder.toString())  ;
        mailVerifyMapper.insert(mailVerify)                                                     ;
        return ServerResponse.createBySuccess("绑定邮件验证信息已发送成功")                      ;
    }

    public ServerResponse bindEmail(String checkCode) {
        MailVerify  mailVerify  =   mailVerifyMapper.getByRandomCode(checkCode)     ;
        System.out.println(mailVerify);
        if(mailVerify ==    null)
        {
            return ServerResponse.createByErrorMsg("验证码无效或已过期")             ;
        }
        ServerResponse sr       =   checkEmail(mailVerify.getEmail())               ;
        if(sr.getStatus()       !=  0)
        {
            return sr                                                               ;
        }
        Date oldTime            =   mailVerify.getDeadline()                        ;
        Date newTime            =   new Date()                                      ;
        long times              =   DateUtil.secondsBetween(oldTime,newTime)        ;
        int  hour               =   (int) (times/60/60)                             ;
        if(hour  >   48)
        {
            mailVerifyMapper.deleteByPrimaryKey(mailVerify.getId())                 ;
            return ServerResponse.createByErrorMsg("验证码已过期,请在收到验" +
                                             "证码48小时内执行激活操作")             ;
        }
        UserInfo    userInfo    =   iUserInfoService.get(mailVerify.getUserInfoId());
        Long state              =   BitOperationUtil.addState(userInfo.getBitState(),
                                                                Const.OP_BIND_EMAIL);
        iUserInfoService.bindEmail(userInfo.getId(),state,mailVerify.getEmail())    ;
        mailVerifyMapper.deleteByPrimaryKey(mailVerify.getId())                     ;
        return ServerResponse.createBySuccessMsg("邮箱绑定成功")                     ;
    }

}
